<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="queryStats" placeholder="状态" clearable style="width: 90px; margin:5px 0 5px 0;" class="filter-item">
        <el-option v-for="item in statsOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="queryType" placeholder="类型" clearable style="width: 90px; margin:5px 0 5px 0;" class="filter-item">
        <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="queryAdAddrType" placeholder="广告地址类型" clearable style="width: 90px; margin:5px 0 5px 0;" class="filter-item">
        <el-option v-for="item in adAddrTypeOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="queryExpire" placeholder="过期类型" clearable style="width: 90px; margin:5px 0 5px 0;" class="filter-item">
        <el-option v-for="item in expireOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-date-picker v-model="queryDate" style="width: 260px; margin:5px 0 5px 0;" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" />
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" />
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="广告编号" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="广告名称 " width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="广告类型" class-name="status-col" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.type | typeCssFilter">
            {{ row.type | typeFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.img"  min-width="70" height="70" />
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statsCssFilter">
            {{ row.status | statsFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" class-name="status-col" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.past_time }}
        </template>
      </el-table-column>
      <el-table-column label="广告类型" class-name="status-col" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.ad_addr_type | categoryCssFilter">
            <a :href="row.ad_addr_type, row.ad_addr | categoryUrl" target="_blank">{{ row.ad_addr_type | categoryFilter }}</a>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.order }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_by_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑者" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_by_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)" />
          <el-button icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(row,$index)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="currentPage" :limit.sync="pageSize" @pagination="fetchData({})" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:30px;">
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="广告类型">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择广告类型" @change="typeOnSelected($event)">
            <el-option v-for="(item, idx) in typeOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告跳转类型">
          <el-select v-model="temp.ad_addr_type" class="filter-item" placeholder="广告跳转类型" @change="addrTypeOnSelected($event)">
            <el-option v-for="(item, idx) in adAddrTypeOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="状态">
            <el-option v-for="(item, idx) in statsOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input v-model="temp.order" />
        </el-form-item>
        <div v-if="ad2Pop === true">
          <el-form-item label="首页弹弹窗仅首次">
            <el-select v-model="temp.ad_one_pop" class="filter-item" placeholder="弹出广告">
              <el-option v-for="(item, idx) in popOptions" :key="item" :label="item" :value="idx" />
            </el-select>
          </el-form-item>
        </div>
        <div v-if="ad2Url === true">
          <el-form-item label="外部url" prop="ad_addr">
            <el-input v-model="temp.ad_addr" />
          </el-form-item>
        </div>
        <div v-if="ad2Product === true">
          <el-form-item label="商品编号" prop="ad_addr">
            <el-input v-model="temp.ad_addr" />
          </el-form-item>
        </div>
        <div v-if="ad2SearchResult === true">
          <el-form-item label="搜索关键词" prop="ad_addr">
            <el-input v-model="temp.ad_addr" />
          </el-form-item>
        </div>
        <el-form-item v-if="ad2Product === true || ad2Url === true || ad2SearchResult === true" label="广告图片">
          <el-upload
            action="/common/common/common/upload"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png,.gif"
            :multiple="false"
            :limit="1"
            :data="adImagesObj"
            :on-preview="handleAdPictureCardPreview"
            :file-list="adImagesArr"
            :on-remove="handleAdPicRemove"
            :before-remove="handleAdPicBeforeRemove"
            :on-success="handleAdPicUploadResult"
            :on-error="handleUploadError"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-input v-model="temp.img" type="hidden" />
          <el-dialog :visible.sync="dialogAdImageVisible" size="tiny">
            <img width="100%" :src="dialogAdImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="过期时间" prop="past_time">
          <el-date-picker type="date" placeholder="选择日期" v-model="temp.past_time" style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, createAd, editAd, deleteAd } from '@/api/ad'
import { getInfo, deleteImage } from '@/api/alibabaProduct'
import Pagination from '@/components/Pagination'

const defaultAdAddrType = ['url', '商品id', '关键词']
export default {
  components: { Pagination },
  filters: {
    statsCssFilter(stats) {
      const statsMap = {
        1: 'success',
        0: 'danger'
      }
      return statsMap[stats]
    },
    statsFilter(stats) {
      const statsMap = {
        1: '启用',
        0: '禁用'
      }
      return statsMap[stats]
    },
    typeCssFilter(type) {
      const typeMap = {
        1: 'success',
        2: 'info',
        3: 'warn',
        4: 'danger',
        5: 'info',
        6: 'info'
      }
      return typeMap[type]
    },
    typeFilter(type) {
      const typeMap = {
        1: '拼团图片',
        2: '淘宝图片',
        3: '拼团banner',
        4: '淘宝banner',
        5: '搜索框广告',
        6: '会员banner',
        7: '首页弹窗广告'
      }
      return typeMap[type]
    },
    categoryCssFilter(category) {
      const cate = category + 1
      const categoryMap = {
        1: 'success',
        2: 'info',
        3: 'warn'
      }
      return categoryMap[cate]
    },
    categoryFilter(category) {
      const categoryMap = {
        1: '外部url',
        2: '商品id',
        3: '关键词'
      }
      console.log(categoryMap[category])

      return categoryMap[category]
    },
    categoryUrl(category, value) {
      if (category === 1) {
        return value
      } else if (category === 2) {
        return '/#/alibaba/alibaba/info?id=' + value
      } else {
        return '#'
      }
    }
  },
  data() {
    const validateName = async(rule, value, callback) => {
      let msg = ''
      if (value) {
        const validParam = {
          page: 1,
          page_size: 1,
          sort: 'desc',
          order: 'id',
          name: value
        }
        if (this.temp.id !== undefined) {
          validParam.id = this.temp.id
        }

        await getList(validParam).then(resp => {
          if (resp.meta.total > 0) {
            msg = '标题已经存在'
          }
        })
      } else {
        msg = '广告标题不能为空'
      }

      if (msg !== '') {
        callback(new Error(msg))
      } else {
        callback()
      }
    }
    const validateUrl = async(rule, value, callback) => {
      let msg = ''

      // 验证temp.ad_addr是不是一个有效的url
      if (this.temp.ad_addr_type === 0) {
        if (value === '') {
          msg = 'url不能为空'
        } else {
          const urlExp = new RegExp(/(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g)
          if (urlExp.test(value) === false) {
            msg = '请输入一个有效的url'
          }
        }
      } else if (this.temp.ad_addr_type === 1) {
        // 验证temp.ad_addr是不是一个有效的商品编号
        if (value === '') {
          msg = '商品编号不能为空'
        } else {
          await getInfo(value).catch(err => {
            msg = err.errmsg
          })
        }
      } else {
        if (value === '') {
          msg = '关键词不能为空'
        }
      }

      if (msg !== '') {
        callback(new Error(msg))
      } else {
        callback()
      }
    }
    return {
      hidden: false,
      listLoading: true,
      // 翻页相关数据 当前页，每页显示条数，排序方式，排序字段，符合条件的搜索结果数，搜索结果
      currentPage: 1,
      pageSize: 10,
      sort: 'desc',
      order: 'id',
      total: 0,
      list: [],
      queryType: '',
      queryStats: '',
      queryExpire: '',
      queryAdAddrType: '',
      queryDate: '',
      // 搜索条件相关数据
      importanceOptions: [1, 2, 3],
      statsOptions: ['隐藏', '显示'],
      popOptions: ['否', '是'],
      typeOptions: ['拼团图片', '淘宝图片', '拼团banner', '淘宝banner', '搜索框广告', '会员banner','首页弹窗广告'],
      expireOptions: ['永不过期'],
      adAddrTypeOptions: defaultAdAddrType,
      // 弹出层数据
      // 是否隐藏弹出层
      dialogFormVisible: false,
      // 弹出层状态(创建、编辑)
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      // 临时数据
      temp: {
        id: undefined,
        name: '',
        type: '',
        status: '',
        past_time: '',
        ad_addr_type: '',
        ad_addr: '',
        ad_one_pop:'',
        img: '',
        order: ''
      },
      roleSelected: '',
      // 下载的loading
      downloadLoading: false,
      downloadData: [],
      // 允许插入图片
      ad2SearchResult: false,
      // 广告跳转至商品
      ad2Product: false,
      // 广告跳转至外部链接
      ad2Url: false,
      //弹窗仅首次
      ad2Pop: false,
      adImagesObj: {},
      adImagesArr: [],
      dialogAdImageUrl: '',
      dialogAdImageVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近3天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 表单验证
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        ad_addr: [{ required: true, trigger: 'blur', validator: validateUrl }]
      }
    }
  },
  mounted() {},
  created() {
    this.fetchData()
  },
  methods: {
    handleFilter() {
      this.currentPage = 1
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        type: '',
        status: '',
        past_time: '',
        ad_addr_type: '',
        ad_addr: '',
        ad_one_pop:'',
        img: '',
        order: ''
      }
    },
    handleAdType(val) {
      this.ad2Product = val === 1
      this.ad2Url = val === 0
      this.ad2SearchResult = val === 2
    },
    addrTypeOnSelected(type){
      if (type === 0) {
        this.ad2Product = false
        this.ad2Url = true
        this.ad2SearchResult = false
      } else if (type === 1) {
        this.ad2Product = true
        this.ad2Url = false
        this.ad2SearchResult = false
      }else {
        this.ad2Product = false
        this.ad2Url = false
        this.ad2SearchResult = true
      }
    },
    typeOnSelected(type) {
      if (type === 4) {
        this.ad2Product = false
        this.ad2Url = false
        this.ad2SearchResult = true
        this.adAddrTypeOptions = ['关键词']
        this.ad2Pop = false
      } else if (type === 6) {
        this.ad2Product = true
        this.ad2Url = true
        this.ad2SearchResult = false
        this.ad2Pop = true
      }else {
        this.ad2Product = true
        this.ad2Url = true
        this.ad2SearchResult = false
        this.ad2Pop = false
        this.adAddrTypeOptions = defaultAdAddrType
        // this.adAddrTypeOptions = ['url', '商品id']
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      this.adImagesObj = {
        id: 0,
        type: 'ad_image'
      }
      this.adImagesArr = []

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = {
            name: this.temp.name,
            type: this.temp.type + 1,
            status: this.temp.status,
            ad_addr_type: this.temp.ad_addr_type + 1,
            ad_addr: this.temp.ad_addr,
            ad_one_pop: this.temp.ad_one_pop,
            img: this.temp.img,
            // order: this.temp.order
          }
          if (this.temp.order) {
            param.order = this.temp.order
          }
          if (this.temp.past_time) {
            param.past_time = this.temp.past_time.toLocaleDateString() + ' ' + this.temp.past_time.toTimeString().split(' ')[0]
          }

          console.log(param)
          createAd(param).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '创建成功',
              message: '管理员创建成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
            this.dialogFormVisible = false
          }).catch(error => {
            console.log('role create error: ' + error)
            this.$notify({
              title: '创建失败',
              type: 'info',
              message: error.errmsg,
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = {
            id: this.temp.id,
            name: this.temp.name,
            type: this.temp.type,
            status: this.temp.status,
            past_time: typeof this.temp.past_time === 'string' ? this.temp.past_time : this.temp.past_time.toLocaleDateString() + ' ' + this.temp.past_time.toTimeString().split(' ')[0],
            ad_addr_type: this.temp.ad_addr_type,
            ad_addr: this.temp.ad_addr,
            ad_one_pop: this.temp.ad_one_pop,
            img: this.temp.img
            // order: this.temp.order
          }
          if (this.temp.order) {
            param.order = this.temp.order
          }
          editAd(param).then(() => {
            this.$notify({
              title: '编辑成功',
              type: 'success',
              message: '广告编辑成功',
              duration: 2000
            })
            this.fetchData()
            this.dialogFormVisible = false
          }).catch(error => {
            this.$notify({
              title: '编辑失败',
              type: 'error',
              message: error.errmsg,
              duration: 2000
            })
          })
        }
      })
    },
    handleDownload() {},
    formatJson(filterVal) {},
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.ad_addr_type = this.temp.ad_addr_type - 1
      this.temp.type = this.temp.type - 1

      this.handleAdType(this.temp.ad_addr_type)

      this.ad2Pop = this.temp.type === 6

      this.adImagesArr = [{
        name: this.temp.name,
        url: this.temp.img,
        id: this.temp.id
      }]

      this.adImagesObj = {
        id: this.temp.id,
        type: 'ad_image'
      }

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleModifyStatus(row, value) {},
    handleDelete(row, idx) {
      const param = { id: row.id }
      deleteAd(param).then(() => {
        this.$notify({
          title: '删除成功',
          message: '广告删除成功',
          type: 'success',
          duration: 2000
        })
        this.fetchData()
        this.dialogFormVisible = false
      }).catch(error => {
        this.$notify({
          title: '删除失败',
          message: error.errmsg,
          type: 'error',
          duration: 2000
        })
      })
    },
    fetchData() {
      this.listLoading = true
      const param = {
        sort: this.sort,
        order: this.order,
        page: this.currentPage,
        page_size: this.pageSize
      }
      if (this.queryStats !== '') {
        this.statsOptions.map((item, idx) => {
          if (this.queryStats === item) {
            param.status = idx
          }
        })
      }
      if (this.queryType !== '') {
        this.typeOptions.map((item, idx) => {
          if (this.queryType === item) {
            param.type = idx + 1
          }
        })
      }
      if (this.queryExpire !== '') {
        this.expireOptions.map((item, idx) => {
          if (this.queryExpire === item) {
            param.expire = idx + 1
          }
        })
      }
      if (this.queryAdAddrType !== '') {
        this.adAddrTypeOptions.map((item, idx) => {
          if (this.queryAdAddrType === item) {
            param.ad_addr_type = idx + 1
          }
        })
      }
      if (this.queryDate !== '' && this.queryDate !== null) {
        param.start_expired_date = this.queryDate[0].toLocaleDateString() + ' ' + this.queryDate[0].toTimeString().split(' ')[0]
        param.end_expired_date = this.queryDate[1].toLocaleDateString() + ' ' + this.queryDate[1].toTimeString().split(' ')[0]
      }

      getList(param).then(response => {
        const { data, meta } = response
        this.list = data
        this.listLoading = false
        this.currentPage = parseInt(meta.current_page)
        this.total = parseInt(meta.total)
      }).catch(error => {
        this.listLoading = false
        this.list = []
        console.log('role get list error: ' + error)
      })
    },
    // 图片上传失败
    handleUploadError(err, file, fileList) {
      const resp = JSON.parse(err.message)
      this.$notify({
        title: '图片上传失败',
        type: 'error',
        message: resp.errmsg,
        duration: 2000
      })
    },
    // 广告图片
    handleAdPictureCardPreview(file) {
      this.dialogMainImageUrl = file.url
      this.dialogMainImageVisible = true
    },
    handleAdPicRemove(file, fileList) {
      console.log(file)
      console.log(fileList)
      const param = {
        url: this.temp.img,
        type: 'ad_image',
        id: this.temp.id
      }
      console.log(param)
      deleteImage(param).then(() => {
        this.$notify({
          title: '图片删除成功',
          type: 'success',
          message: '图片删除成功',
          duration: 2000
        })
      }).catch(error => {
        this.$notify({
          title: '图片删除失败',
          type: 'error',
          message: error.errmsg,
          duration: 2000
        })
      })
    },
    // 广告图片
    handleAdPicBeforeRemove(file, fileList) {
      // this.temp.img = ''
    },
    // 广告图片
    handleAdPicUploadResult(response, file, fileList) {
      console.log(response.result.data.file)
      this.temp.img = response.result.data.file
      console.log(this.temp)
    }
  }
}
</script>
<style scoped>
  .filter-container {
    background: #fff;
    padding: 32px 16px;
  }
</style>
